package com.GLM.Viewer.Friends;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.GLM.Constants.Constant;
import com.GLM.Entity.UserInfoDetailEntity;
import com.GLM.Tools.DB.DAO.UserInfoDAO;
import com.GLM.Tools.Utils.Image.AsynImageLoader;
import com.GLM.Tools.Utils.JSON.JSONResponse;
import com.GLM.Tools.Utils.JSON.JSONUtil;
import com.GLM.Tools.Utils.JSON.JSONResponse.Status;
import com.GLM.Viewer.R;
import com.GLM.Viewer.Customized.Panel;
import com.GLM.Viewer.Customized.Panel.OnPanelListener;
import com.GLM.Viewer.Users.UserInfoDetailActivity;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.NavUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.AdapterView.OnItemClickListener;

public class FriendsAttentionActivity extends Activity implements OnPanelListener {

	private final static int FRIENDLIST_LOADING = 111;
	private final static int FRIENDLIST_LONDED = 222;
	private ListView mFriendsList;
	private SimpleAdapter mFriendsAdapter;
	private List<Map<String, Object>> mFriendsItems = new ArrayList<Map<String, Object>>();
	private String[] friendsItemKeys = new String[] { "nickname", "friendinfo" };
	private int[] friendsItemIds = new int[] { R.id.friends_myfriends_name, R.id.friends_myfriends_infos};
	private Map<String, String> friendsPics = new HashMap<String, String>();
	private int user_id;
	private Button classBtn;
	private String mCurrentTitle;
	private int loadClazz = 2;
	private Panel mSlidingDrawer;
	private int[] navIds = new int[] { R.string.friends_myfriends_notuse, R.string.friends_myfriends_mycare, R.string.friends_myfriends_careme, R.string.friends_myfriends_careeach };
	private AsynImageLoader imageLoader = new AsynImageLoader();
	private Map<Integer, Integer> FriendsMap = new HashMap<Integer, Integer>();
	private int screenWidth;
	private int screenHeight;
	RelativeLayout layout;
	private Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			Thread thread;
			switch (msg.what) {
			case FRIENDLIST_LOADING:
				mFriendsItems.clear();
				FriendsMap.clear();
				mFriendsAdapter = null;
				thread = new Thread(new Runnable() {
					public void run() {
						
						initFriendsList(loadClazz);
						mFriendsAdapter = new SimpleAdapter(FriendsAttentionActivity.this, mFriendsItems, R.layout.view_friends_attention_listitem, friendsItemKeys, friendsItemIds);
						mHandler.sendEmptyMessage(FRIENDLIST_LONDED);
					}

				});
				thread.start();
				break;

			case FRIENDLIST_LONDED:
				if (mFriendsAdapter != null && mFriendsItems.size() >0) {
					layout.setBackgroundDrawable(getResources().getDrawable(R.drawable.glm_background));
					mFriendsList.setAdapter(mFriendsAdapter);
					bindItemClick();
				}else{
					Paint paint = new Paint();
					paint.setTextSize(20);
					paint.setAntiAlias(true);
					String str = getString(R.string.friends_no_friendsmsg);
					Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.glm_background);
					Canvas canvas = new Canvas(bitmap);
					canvas.drawText(str,screenWidth/2-str.length()*9 , screenHeight/2, paint);
					
					Drawable drawable = new BitmapDrawable(bitmap);
					layout.setBackgroundDrawable(drawable);
				}
				break;
			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.view_friends_attention);
		screenWidth = getWindowManager().getDefaultDisplay().getWidth();
		screenHeight = getWindowManager().getDefaultDisplay().getHeight();
		layout = (RelativeLayout)findViewById(R.id.friends_attention_layout);
		user_id = UserInfoDAO.getUserInfo(FriendsAttentionActivity.this).getUserId();
		initSlidingDrawer();
		classBtn = (Button) findViewById(R.id.friends_class_button);
		mFriendsList = (ListView) findViewById(R.id.friends_myfriends_listview);
	
		final SharedPreferences sp = getSharedPreferences(Constant.SHAREDNAME, MODE_PRIVATE);
		boolean isshow = sp.getBoolean(Constant.FANSFRIENDACTIVITY, true);
		final ImageView tipView = (ImageView)findViewById(R.id.tipView);
		if(!isshow){
			tipView.setVisibility(View.VISIBLE);
			tipView.setOnTouchListener(new OnTouchListener() {
				
				public boolean onTouch(View v, MotionEvent event) {
					// TODO Auto-generated method stub
					tipView.setVisibility(View.GONE);
					tipView.setImageBitmap(null);
					Editor editor = sp.edit();
					editor.putBoolean(Constant.FANSFRIENDACTIVITY, true);
					editor.commit();
					System.gc();
					return true;
				}
			});
		}
		mHandler.sendEmptyMessage(FRIENDLIST_LOADING);
	}

	private void initSlidingDrawer() {
		mSlidingDrawer = (Panel) findViewById(R.id.glmSlidingdrawer);
		mSlidingDrawer.setOnPanelListener(this);
		List<Map<String, Object>> items = initGridViewItems();
		GridView gv = (GridView) findViewById(R.id.mycontent);
		gv.setAdapter(new SimpleAdapter(this, items, R.layout.view_navgrid, new String[] { "key" }, new int[] { R.id.navgrid_button }));
		gv.setOnItemClickListener(new OnItemClickListener() {

			@SuppressWarnings("unchecked")
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				HashMap<String, Object> item = (HashMap<String, Object>) parent.getItemAtPosition(position);
				if (mSlidingDrawer.isOpen()) {
					mCurrentTitle = (String) item.get("key");
					classBtn.setText(mCurrentTitle);
					mSlidingDrawer.setOpen(false, true);
					int loadid = position + 1;
					Log.d("loadclazz", loadid+"");
					if(loadid>1){
						loadClazz = loadid;
						mHandler.sendEmptyMessage(FRIENDLIST_LOADING);
					}
					
				}
			}
		});
	}

	private List<Map<String, Object>> initGridViewItems() {
		List<Map<String, Object>> listItems = new ArrayList<Map<String, Object>>();
		for (int i = 0; i < navIds.length; i++) {
			Map<String, Object> item = new HashMap<String, Object>();
			item.put("key", getString(navIds[i]));
			listItems.add(item);

		}
		return listItems;
	}

	public void onPanelClosed(Panel panel) {
		// TODO Auto-generated method stub

	}

	public void onPanelOpened(Panel panel) {
		// TODO Auto-generated method stub

	}

	
	public void bindItemClick(){
		mFriendsList.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View arg1, int position,
					long arg3) {
				// TODO Auto-generated method stub
				int friendId = FriendsMap.get(position);
				Intent intent = new Intent(FriendsAttentionActivity.this,UserInfoDetailActivity.class);
				intent.putExtra(Constant.INTENT_USER_ID, friendId);
				startActivity(intent);
			}
		});
		mFriendsList.setOnScrollListener(scrollListener);
	}
	
	public OnScrollListener scrollListener = new OnScrollListener() {
		
		public void onScrollStateChanged(AbsListView view, int scrollState) {
			// TODO Auto-generated method stub
			
		}
		
		public void onScroll(AbsListView view, int firstVisibleItem,
				int visibleItemCount, int totalItemCount) {
			// TODO Auto-generated method stub
			LoadFriendPic();
		}
	};
	
	public void LoadFriendPic() {
		int count = mFriendsList.getChildCount();
		for (int i = 0; i < count; i++) {
			View view = mFriendsList.getChildAt(i);
			ImageView imageView = (ImageView) view.findViewById(R.id.friends_myfriens_avar);
			String key = String.valueOf(i);
			String picurl = friendsPics.get(key);

			if (picurl != null && picurl != "") {
				Log.d("friendsUrl", picurl);
				imageLoader.showImageAsyn(imageView, Constant.URL_USER_MIDDLE + picurl, R.drawable.glm_white);

			}
		}
	}
	
	
	public void gobackButton_OnClick(View v) {
		NavUtils.navigateUpTo(FriendsAttentionActivity.this, new Intent(FriendsAttentionActivity.this, FriendsMainActivity.class));
	}

	public void initFriendsList(int clazz) {
		JSONObject jsonData = new JSONObject();
		JSONResponse jsonResponse = null;
		try {
			jsonData.put(Constant.PARAM_CLASSID, user_id );
			jsonData.put(Constant.PARAM_FRIENDS_CLASS, clazz);
			jsonData.put(Constant.PARAM_USERID_ONE, user_id);
			jsonResponse = JSONUtil.postRequest(Constant.REQ_WAY_GETFRIENDSSMS, jsonData);
			if (jsonResponse.getStatus() != Status.ERR) {
				int status = -1;
				JSONObject data = jsonResponse.getData();
				status = data.getInt(Constant.RESP_STATUS);
				if (status == Constant.RESP_STATUS_SUCCESS) {
					JSONArray jsonArray = data.getJSONArray(Constant.RESP_PARTY_USERS);

					initFriendItemFromJson(jsonArray);
				}

			}
		} catch (Exception e) {
			// TODO: handle exception

		}
	}

	public void initFriendItemFromJson(JSONArray jsonArray) throws JsonSyntaxException, JSONException {
		Gson gson = new Gson();
		String msg = getString(R.string.friends_myfriends_message);
		String fans = getString(R.string.friends_myfriends_fans);
		String party = getString(R.string.friends_myfriends_party);
		for (int i = 0; i < jsonArray.length(); i++) {
			UserInfoDetailEntity entity = gson.fromJson(jsonArray.getJSONObject(i).toString(), UserInfoDetailEntity.class);
			Map<String, Object> item = new HashMap<String, Object>();
			String relname = entity.getUd_relname();
			if(relname == null || relname == ""){
				item.put("nickname", entity.getUd_nickname());
			}
			else {
				item.put("nickname", relname);
			}
			item.put("friendinfo", msg+entity.getMsg()+"  "+fans+entity.getFollows()+"  "+party+entity.getMeetCount());
			mFriendsItems.add(item);
			Log.d("Loc_id>", entity.getUser_avatar() + "");
			friendsPics.put(String.valueOf(i), entity.getUser_avatar());
		    FriendsMap.put(i, entity.getUser_id());
		}
	}

}